package com.fingard.dsp.bank.directbank.cmb01;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.fngrd01.util.StringHelper;
import com.fingard.dsp.bank.helpers.DataFileHelper;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.ReqQryReceipt;
import com.fingard.io.FileHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CMB01SyncTask extends CMB01Base {

    private ReqQryReceipt p_reqReceipt;
    private DataFileHelper dFileHelper=new DataFileHelper(this);

    public CMB01SyncTask(ReqQryReceipt p_reqReceipt) {
        this.p_reqReceipt=p_reqReceipt;
    }

    private ExecutorService executorService = Executors.newFixedThreadPool(1);

    public void downloadReceipt() {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                StringBuilder logSb = new StringBuilder();
                try {
                    setSbLog(logSb);

                    Calendar tmpCalendarFrom = Calendar.getInstance();
                    tmpCalendarFrom.setTime(p_reqReceipt.getDateFrom());

                    Calendar tmpCalendarTo = Calendar.getInstance();
                    tmpCalendarTo.setTime(p_reqReceipt.getDateTo());

                    int tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                    int tmpIntTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));

                    //按日循环
                    String printFlagStr = getValueAsString("printFlag");
                    if (StringHelper.isNullOrEmpty(printFlagStr)) {
                        WriteBankLogLn2("配置文件缺失招行回单打印标志配置（1:未打印，2:已打印）:<printFlag></printFlag>，当前使用默认值1。");
                        printFlagStr = "1";
                    }
                    String[] printFlags = printFlagStr.split(",");
                    while (tmpIntFrom <= tmpIntTo) {//按日查询

                        for (String printFlag : printFlags) {
                            try {
                                printFlag = printFlag.trim();
                                if (!"1".equals(printFlag) && !"2".equals(printFlag)) {
                                    WriteBankLogLn("配置文件招行回单打印标志配置不规范：" + printFlag);
                                    continue;
                                }
                                boolean hasCacheData = false;
                                Date dateNow = new Date();
                                int intToday = Integer.parseInt(Format.Date8Format.format(dateNow));

                                int intFromStep = tmpIntFrom;
                                Date fromDateStep = tmpCalendarFrom.getTime();

                                String dataFilePath = dFileHelper.getBankReceiptDataFile(fromDateStep, printFlag + "_" + p_reqReceipt.actNum);
                                File dataFile = new File(dataFilePath);
                                if (dataFile.exists()) {
                                    WriteBankLogLn(intFromStep + "的回单已执行过下载，如需重新获取，请删除文件" + dataFilePath);
                                    //retAts.respCode = "0";
                                    //retAts.respInfo = intFromStep + "的回单已执行过下载";
                                    continue;
                                }
                                WriteBankLogLn("执行" + intFromStep + "的回单数据查询");
                                //第一步查回单数据
                                CMB01Header tmpBnkHeader = new CMB01Header();
                                tmpBnkHeader.FUNNAM = "SDKCSFDFBRT";

                                XmlTextWriter xmlWriter = new XmlTextWriter();
                                xmlWriter.autoFormat = false;
                                writeCommonHeader(xmlWriter, tmpBnkHeader);

                                xmlWriter.writeStartElement("CSRRCFDFY0");
                                xmlWriter.writeElementString("EACNBR", p_reqReceipt.actNum); /* 账号 */
                                xmlWriter.writeElementString("BEGDAT", "" + intFromStep); /* 开始日期 */
                                xmlWriter.writeElementString("ENDDAT", "" + intFromStep); /* 结束日期 */
                                xmlWriter.writeElementString("RRCFLG", printFlag); /* 打印标志 */
                                xmlWriter.writeElementClosed("BEGAMT"); /* 最小金额 */
                                xmlWriter.writeElementClosed("ENDAMT"); /* 最大金额 */
                                xmlWriter.writeElementClosed("RRCCOD"); /* 回单代码 */
                                xmlWriter.writeEndElement();
                                xmlWriter.writeEndDocument();

                                String[] tmpStrRet1 = sendToBank(xmlWriter.toXmlString());
                                //测试用
                                //tmpStrRet1[0] = "";
                                //tmpStrRet1[1] = FileHelper.readFileText("D:\\11.txt", "utf-8");
                                //测试用
                                boolean doStep2 = false;
                                if (tmpStrRet1[0].length() == 0) {
                                    StringBuilder tmpSbMsg = new StringBuilder();
                                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet1[1], tmpSbMsg);
                                    if (tmpBkReader != null) {
                                        String tmpRetCode = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/RETCOD");
                                        String tmpERRMSG = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/ERRMSG");
                                        if ("0".equals(tmpRetCode)) {
                                            doStep2 = true;
                                            if (getBankConfig().getValueAsBool("alwaysCacheReceiptData")) {
                                                FileHelper.writeFile(dataFile, tmpStrRet1[1], FGBiz.dspCenter.charset);
                                                hasCacheData = true;
                                            }
                                        } else {
                                            WriteBankLogLn(tmpRetCode + "-" + tmpERRMSG);
                                        }
                                    } else {
                                        WriteBankLogLn(tmpSbMsg);
                                    }
                                } else {
                                    WriteBankLogLn(tmpStrRet1[0] + "-" + tmpStrRet1[1]);
                                }
                                if (!doStep2) {
                                    continue;
                                }
                                WriteBankLogLn("执行" + intFromStep + ("1".equals(printFlag) ? "未打印" : "已打印") + "的回单文件下载");


                                tmpBnkHeader = new CMB01Header();
                                tmpBnkHeader.FUNNAM = "SDKCSFDFBRTIMG";

                                xmlWriter = new XmlTextWriter();
                                xmlWriter.autoFormat = false;
                                writeCommonHeader(xmlWriter, tmpBnkHeader);

                                xmlWriter.writeStartElement("CSRRCFDFY0");
                                xmlWriter.writeElementString("EACNBR", p_reqReceipt.actNum); /* 账号 */
                                xmlWriter.writeElementString("BEGDAT", "" + intFromStep); /* 开始日期 */
                                xmlWriter.writeElementString("ENDDAT", "" + intFromStep); /* 结束日期 */


                                xmlWriter.writeElementString("RRCFLG", printFlag); /* 打印标志 */
                                xmlWriter.writeElementClosed("BEGAMT"); /* 最小金额 */
                                xmlWriter.writeElementClosed("ENDAMT"); /* 最大金额 */
                                xmlWriter.writeElementClosed("RRCCOD"); /* 回单代码 */
                                xmlWriter.writeEndElement();
                                xmlWriter.writeEndDocument();

                                String[] tmpStrRet2 = sendToBank(xmlWriter.toXmlString());
                                //测试用
                                //tmpStrRet2[0] = "";
                                //tmpStrRet2[1] = "<?xml version=\"1.0\" encoding=\"GBK\"?><CMBSDKPGK><INFO><DATTYP>2</DATTYP><ERRMSG>SDKM199: 回单图片查询成功！</ERRMSG><FUNNAM>SDKCSFDFBRTIMG</FUNNAM><LGNNAM>yangliu-计财</LGNNAM><RETCOD>0</RETCOD></INFO></CMBSDKPGK>";
                                //测试用
                                if (tmpStrRet2[0].length() == 0) {
                                    StringBuilder tmpSbMsg = new StringBuilder();
                                    XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet2[1], tmpSbMsg);
                                    if (tmpBkReader != null) {
                                        String tmpRetCode = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/RETCOD");
                                        if ("0".equals(tmpRetCode)) {
                                            //下载成功之后，保存回单数据文件
                                            boolean saveCacheData = true;
                                            if (intFromStep < intToday) {
                                                double diffDays = DateHelper.getDifferDays(dateNow, fromDateStep);
                                                if (diffDays < 2) {//昨日需判断几时可以缓存
                                                    int cacheHourSet = getBankConfig().getValueAsInt("receiptCacheHour");
                                                    int stepHour = DateHelper.getHour(dateNow);
                                                    if (stepHour < cacheHourSet) {
                                                        saveCacheData = false;
                                                        WriteBankLogLn("当天" + cacheHourSet + "时前不缓存昨日回单数据，保存为临时文件");

                                                    }
                                                }
                                            } else {
                                                saveCacheData = false;
                                                WriteBankLogLn("当天不缓存回单数据，保存为临时文件");
                                            }
                                            if(!saveCacheData){
                                                if(dataFilePath.endsWith(".txt")){
                                                    dataFilePath = dataFilePath.replace(".txt", ".tmp.txt");
                                                }else{
                                                    dataFilePath += ".tmp";
                                                }
                                                WriteBankLogLn("临时文件路径："+dataFilePath);
                                                dataFile = new File(dataFilePath);
                                            }
                                            FileHelper.writeFile(dataFile, tmpStrRet1[1], FGBiz.dspCenter.charset);
                                            //retAts.respCode = "0";
                                            //retAts.respInfo = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/ERRMSG");
                                            WriteBankLogLn(tmpBkReader.getFirstText("/CMBSDKPGK/INFO/ERRMSG"));
                                        } else {
                                            //retAts.respCode = "-1";
                                            //retAts.respInfo = tmpBkReader.getFirstText("/CMBSDKPGK/INFO/ERRMSG");
                                            WriteBankLogLn(tmpBkReader.getFirstText("/CMBSDKPGK/INFO/ERRMSG"));
                                        }
                                    } else {
                                        //retAts.respCode = "-1";
                                        //retAts.respInfo = tmpSbMsg.toString();
                                        WriteBankLogLn(tmpSbMsg.toString());
                                    }
                                } else {
                                    //retAts.respCode = "-1";
                                    //retAts.respInfo = tmpStrRet2[0] + tmpStrRet2[1];
                                    WriteBankLogLn(tmpStrRet2[0] + tmpStrRet2[1]);
                                }
                            } catch (Exception ex) {
                                WriteBankLogLn(ex);
                            }
                        }//是否打印

                        tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                        tmpIntFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                    }
                } catch (Exception ex) {
                    //ex.printStackTrace();
                    //retAts.respCode = "-1";
                    //retAts.respInfo = ex.getMessage();
                    WriteBankLogLn(ex.getMessage());
                }finally {
                    String tmpDateDir = Format.DateForLogFormat.format(new Date()).replace("-", File.separator);
                    String tmpSubFileName = FGBiz.dspCenter.bankLogsFirstDir + File.separator + tmpDateDir + File.separator + "CMB01" + File.separator + "SyncTask-downloadReceipt" + "_" + p_reqReceipt.actNum + "_" + Format.DateTime14Format.format(new Date()) + "_" + UUID.randomUUID() + ".txt";
                    String tmpLogFile = FGBiz.dspCenter.bankLogsDirPath + File.separator + tmpSubFileName;
                    try {
                        FileHelper.writeFile(tmpLogFile, logSb);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }
        });
    }
}
